package cn.edu.hbwe.book.servlet.user;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import cn.edu.hbwe.book.entity.User;
import cn.edu.hbwe.book.exception.RegistException;
import cn.edu.hbwe.book.service.UserService;
import cn.edu.hbwe.book.utils.ActiveCodeUtils;


/**
 * Servlet implementation class RegistUserServlet
 */
public class UserRegistServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		//校验验证码
		String code = request.getParameter("code");
		String serverCode = (String) request.getSession().getAttribute("serverCode");
		if(!serverCode.equalsIgnoreCase(code)) {
			request.setAttribute("codeError", "输入验证码错误！");
			request.getRequestDispatcher("/bookweb/register.jsp").forward(request, response);
			return;
		}
		//封装注册参数到user
		User user = new User();
		try {
			BeanUtils.populate(user, request.getParameterMap());
			// 封裝激活码
			user.setActiceCode(ActiveCodeUtils.createActiveCode());
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}

		//调用service中对应的方法
		UserService usi=new UserService();
		try {
			usi.userRegist(user);
			//注册成功
			response.sendRedirect(request.getContextPath() + "/bookweb/registersuccess.jsp");
			return;
		} catch (Exception e) {
			String error = e.getMessage();
			response.getWriter().write(error);
		} 
	}

}
